package com.xx.sg.schedule;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xx.sg.own.entity.Dept;
import com.xx.sg.own.entity.FireInfo;
import com.xx.sg.own.service.DeptService;
import com.xx.sg.own.service.FireInfoService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;


@Component
public class SatelliteAlarmTask {

    public static JSONArray SatelliteAlarmJson = null;

    @Value("${transfer.host}")
    private String HOST;
    @Value("${transfer.hh.prefix}")
    private String HH_PREFIX;
    @Value("${transfer.hh.userName}")
    private String userName;
    @Value("${transfer.hh.password}")
    private String password;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private FireInfoService fireInfoService;
    @Autowired
    private DeptService deptService;

    // 启动时执行一次
//    @PostConstruct
//    public void init() {
//        task();
//    }

    // 每5分钟执行一次（从上次开始算）
//    @Scheduled(fixedRate = 5 * 60 * 1000)
    @Scheduled(cron = "0 */5 * * * ?")
    public void scheduledTask() {
        task();
    }

    // 任务逻辑提取到方法中，避免重复代码
    private void task() {
        // 实际业务逻辑
        String url = String.format("%s%s/api/Satellite/GetAlarmByInterval?token=%s", HOST, HH_PREFIX, getToken());
        String result = restTemplate.getForObject(url, String.class);
        SatelliteAlarmJson = JSON.parseArray(result);

        for (int i = 0; i < SatelliteAlarmJson.size(); i++) {
            JSONObject alarm = SatelliteAlarmJson.getJSONObject(i);
            String sourceId = alarm.getString("FireNo");
            LambdaQueryWrapper<FireInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FireInfo::getSourceId, sourceId)
                    .eq(FireInfo::getClassify, "satellite");
            List<FireInfo> fireInfoList = fireInfoService.list(wrapper);
            if (fireInfoList.isEmpty()) {
                LocalDateTime dateTime = LocalDateTime.parse(alarm.getString("ObservationDateTime"));

                String visibleLightImage = "http://web.ehaohai.com:2018" + alarm.getString("VisibleLightImageAddress");
                String IRImage = "http://web.ehaohai.com:2018" + alarm.getString("IRImageAddress");
                FireInfo fireInfo = FireInfo.builder()
                        .sourceId(sourceId)
                        .datetime(dateTime)
                        .name(alarm.getString("Satellite"))
                        .longitude(alarm.getDouble("Longitude"))
                        .latitude(alarm.getDouble("Latitude"))
                        .classify("satellite")
                        .picture(visibleLightImage + "," + IRImage)
                        .build();
                Dept dept = deptService.selectDeptByPoint(fireInfo.getLongitude(), fireInfo.getLatitude());
                if (dept == null) {
                    fireInfo.setRegionId("00115");
                } else {
                    fireInfo.setRegionId(dept.getId());
                }
                fireInfoService.save(fireInfo);
            }
        }
    }

    private String getToken() {
        String url = String.format("%s%s/api/Account/Login?userName=%s&password=%s", HOST, HH_PREFIX, userName, password);
        String result = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("message");
    }

}
